package 可重入锁.带Condition条件;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockCondition implements Runnable{
    private static ReentrantLock lock = new ReentrantLock();
    private static Condition empty = lock.newCondition();
    private Condition full = lock.newCondition();

    @Override
    public void run() {
        try {
            lock.lock();
            empty.await();
            System.out.println("线程从empty条件上继续运行");
            lock.unlock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /*
        1，写condition.await() condition.signal() 前后要写lock(),unlock()类型操作，不然运行不了
            如果condition先signal,在await()，那线程也会一直卡在condition上

        2，Condition的await和signal前后要有可重入锁的lock和unlock，不然运行报错！
     */
    public static void main(String[] args) throws InterruptedException {
        ReentrantLockCondition reentrantLockCondition = new ReentrantLockCondition();
        Thread thread = new Thread(reentrantLockCondition);
        thread.start();
        Thread.sleep(1000);// 保证signal在await后面执行！
        lock.lock();
        empty.signal();
        lock.unlock(); //不写也执行不了。因为不释放锁，就算empty条件线程被唤醒，但是这个线程类似.lock()得不到锁，卡在了请求锁的路上
    }
    //结果：
    //      线程从empty条件上继续运行
}
